/**
 * Description:
 * Created by GoLand.
 * User: Vijay <1937832819@qq.com>
 * Date: 2020/8/20
 * Time: 23:09
 */
package middlewares

import (
	"blogApi/commons"
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	"github.com/dgrijalva/jwt-go"
	"github.com/syyongx/php2go"
	"strings"
)

//配置不需要登录的url
var openUrl = []string{
	"test:index",
	"user:login",
	"admin:login",
	"captcha:check",
}

func Init() {
	// 登录验证
	var FilterFunc = func(ctx *context.Context) {
		helper := commons.Helper{}
		// 检查登录
		currentUrl := ctx.Request.URL.RequestURI()
		controllerName, actionName := getControllerAndAction(currentUrl)
		conCct := php2go.Strtolower(controllerName + ":" + actionName)
		isOpen := php2go.InArray(conCct, openUrl)
		if isOpen == false {
			beego.Debug("需要验证登陆\n")
			token, e := helper.ParseToken(ctx)
			if e != nil {
				ctx.Output.Header("Content-Type", "application/json")
				resBody, err := json.Marshal(OutResponse(1, "获取失败", e))
				if err != nil {
					panic(err)
				}
				ctx.Output.Body(resBody)
				return
			}
			claims, ok := token.Claims.(jwt.MapClaims)
			if !ok {
				ctx.Output.Header("Content-Type", "application/json")
				resBody, err := json.Marshal(OutResponse(1, "获取失败", "token 验证失败"))
				if err != nil {
					panic(err)
				}
				ctx.Output.Body(resBody)
				return
			}
			admin := claims["username"].(string)
			beego.Debug("用户：", admin)
		} else {
			beego.Debug("不需要登陆\n")
		}
	}

	// /api/* 这种路由需要登录
	beego.InsertFilter("/api/*", beego.BeforeRouter, FilterFunc)
}

/**
返回控制器和方法名
*/
func getControllerAndAction(url string) (controllerName, actionName string) {
	con, act := "", ""
	if php2go.Strpos(url, "/api", 0) != -1 {
		stringSlice := strings.Split(url, "/")
		if len(stringSlice) >= 3 {
			con = stringSlice[2]
		}
		if len(stringSlice) >= 4 {
			act = stringSlice[3]
		}
	}
	return con, act
}
